<template>
  <view :class="theme">
    <!-- <view class="header fd-row ai-center bg-21">
      <u-image @click="uniNavigator({ type: 'navigateBack' })" width="50" height="50"
        src="/static/img/otc/icon-back.svg" />
      <view class="f1 ml-30 mr-30 fd-row ai-center bg-22 br-50" style="height: 30px;">
        <input @confirm="search" v-model="sellOrders.search" confirm-type="search"
          class="f1 fs-28 pl-30 pr-30 color-2 height-100percent" type="text" placeholder="输入手机号搜索订单" />
        <button @click="search" hover-class="tap-hover" class="fs-28 br-50 color-3 bg-23" style="line-height: 30px;">
          搜索
        </button>
      </view>

      <u-image @click="uniNavigator({ url: '/pages/client/otc/order' })" width="50" height="50"
        src="/static/img/otc/icon-order.svg" />
    </view> -->
    <view class="br-20 bg-base p-30 m-30 fd-row ai-center jc-sb text-center"
      style="box-shadow: 0 0 24rpx 0 rgba(0,0,0,0.5); color: #b9c1d9;">
      <view>
        <text class="fs-32 fw-700 color-primary">
          {{ tradeInfo?.refer_price || 0 }} CNY
        </text>
        <text class="mt-12 fs-22 color-9">今日指导价</text>
      </view>
      <view>

        <text class="fs-32 fw-700 color-primary">
          {{ tradeInfo?.today_sell || 0 }}
        </text>
        <text class="mt-12 fs-22 color-9">今日成交</text>
      </view>
      <view>
        <text class="fs-32 fw-700 color-primary">
          {{ tradeInfo?.today_apply || 0 }}
        </text>
        <text class="mt-12 fs-22 color-9">总求购</text>
      </view>
    </view>

    <view @click="uniNavigator({ url: '/pages/client/otc/order' })" class="f1 relative br-10 oh" style="margin: 0 30rpx;">
      <u-image :custom-style="{ transform: `rotateY(180deg)` }" class="absolute" width="100%" height="100%"
        src="/static/img/otc/bg-section_3.png" />
      <view class="relative fd-row ai-center p-30">
        <view class="f1 fd-row ai-center">
          <u-image width="96" height="96" src="/static/img/otc/icon-order.png" />
          <view class="ai-center relative ml-40">
            <view class="absolute bottom-0 left-16 width-90percent height-8 br-30 opacity-06 bg-5"
              style="background-color: #36c9e4;" />
            <text class="relative color-2 fs-36" style="z-index: 1; text-shadow: 0 0 8rpx rgba(86, 189, 252, 0.6);">
              订单中心
            </text>
          </view>
        </view>
        <button class="fd-row br-30 border-none lh-2" style="background-color: #2e9bff;" plain>
          <text class="color-2 fs-24 fw-700 mr-12">查看</text>
          <u-icon size="20" :color="$config.COLOR_2" name="play-right-fill" />
        </button>
      </view>
    </view>

    <u-sticky :bg-color="$config.COLOR_7">
      <view class="fd-row jc-sb p-24 flex-wrap bg-22">
        <label @click="checkedPriceRange(index)" v-for="(item, index) in priceRange.list" :key="index"
          :style="{ boxShadow: priceRange.current === index ? `0 0 12rpx #56bdfc` : `unset`, transition: `all 0.1s linear` }"
          :class="[priceRange.current === index ? 'color-27' : 'color-9', 'bg-21 br-10 width-88 lh-2 jc-center m-12']">
          {{ item.text }}
        </label>
      </view>
    </u-sticky>
    <view class="pl-30 pr-30"
      style="margin-bottom: constant(safe-area-inset-bottom); margin-bottom: env(safe-area-inset-bottom);">
      <view class="mb-20">
        <view v-for="item in sellOrders.list" :key="item.id" class="relative bg-21 br-20 oh mb-20">
          <u-image class="absolute" width="100%" height="100%" src="/static/img/otc/bg-section_2.png" />
          <view class="relative p-30">
            <view class="fd-row ai-center">
              <view class="fd-row ai-center f1">
                <u-image width="60" height="60" radius="50%" :src="item.avatar || `/static/logo.png`" />
                <text class="ml-20 color-2 fs-28">{{ item.username || "-" }}</text>
              </view>
              <text v-if="item.vip" class="fs-24 fw-700 text-center"
                style="width: 150rpx; font-style: italic; background-image: linear-gradient(90deg, #56bdfc, #b99cf9); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
                {{ item.vip || "-" }}
              </text>
            </view>
            <label class="mt-24 ai-baseline">
              <text class="fs-20">￥</text>
              <text class="fs-40 fw-700">{{ item.price || "0.00" }}</text>
            </label>
            <label class="mt-24">
              <text class="color-9">数量</text>
              <text class="ml-12">{{ item.num || 0 }}个</text>
            </label>
            <view class="mt-24 fd-row jc-sb">
              <label>
                <text class="color-9">类型</text>
                <text class="ml-12">星核</text>
              </label>
              <button @click="sell(item)" hover-class="tap-hover" class="fs-28 br-50 color-3 bg-23 lh-50 m-0">出售</button>
            </view>
          </view>
        </view>
      </view>
      <u-loadmore margin-bottom="20" :status="sellOrders.cache.status" is-dot />
    </view>

    <view class="footer bg-21">
      <navigator url="/pages/client/otc/publish" hover-class="tap-hover"
        class="fs-36 fw-700 br-50 color-2 bg-23 text-center" style="line-height: 44px; margin: 14px 50rpx;">
        发布求购
      </navigator>
    </view>

    <u-popup v-model="showPopup.sell" @input="changePopup($event, 'sell')" mode="bottom" closeable :mask-close-able="true"
      close-icon-color="#fff">
      <view class="bg-21" style="border-radius: 20rpx 20rpx 0 0;">
        <label class="fs-36 p-30 jc-center fw-700">卖出</label>
        <view class="p-30">
          <view class="fd-row ai-center">
            <u-image width="60" height="60" radius="50%" :src="currentOrder.avatar || `/static/logo.png`" />
            <text class="ml-10 fs-28">{{ currentOrder.username || "-" }}</text>
          </view>
          <label class="jc-sb mt-50 fs-28">
            <text>买入单价</text>
            <text>{{ currentOrder.price || "0.00" }}CNY</text>
          </label>
          <label class="jc-sb mt-30 fs-28">
            <text>买入数量（星核）</text>
            <text>{{ currentOrder.num || 0 }}个</text>
          </label>
          <!-- <view class="fd-row ai-center jc-sb mt-30 fs-28">
            <text>交易方式</text>
            <view class="fd-row">
              <block v-for="(option, key) in payOptions" :key="key">
                <view v-if="currentOrder.pay_type?.includes(option.value)" class="ml-40 fd-row ai-center">
                  <view :style="{ backgroundColor: option.color }" class="width-4 height-30" />
                  <text class="ml-10">{{ option.text }}</text>
                </view>
              </block>
            </view>
          </view> -->
          <label class="mt-50 jc-center">
            <text class="fs-28">总价：</text>
            <text class="fs-36 color-27 fw-700">{{ (currentOrder.num * currentOrder.price).toFixed(2) }}CNY</text>
          </label>
          <button @click="confirmSell" hover-class="tap-hover" class="fs-36 fw-700 br-50 color-2 bg-23"
            style="line-height: 44px; margin: 24px 0 0;">卖给TA</button>
        </view>
      </view>
    </u-popup>
    <u-popup v-model="showPopup.payable" @input="changePopup($event, 'payable')" mode="center" closeable
      :mask-close-able="false" close-icon-color="#fff">
      <view class="br-20 bg-21 p-30 oh" style="width: 600rpx;">
        <label class="fs-36 fw-700">确认收款方式</label>

        <block v-for="(option, key) in (payOptions as AnyObject)" :key="key">
          <view v-if="currentOrder.pay_type?.includes(option.value)">
            <view @click="setPayOption(key as string)" class="mt-40 fd-row ai-center">
              <u-image width="50" height="50" :src="`/static/img/otc/icon-${key}.png`" />
              <text class="f1 ml-20 fs-28 color-9">{{ option.text }}</text>
              <u-image width="40" height="40" src="/static/img/otc/icon-edit.svg" />
            </view>
            <view v-if="option.info.account" class="ml-70 fs-28 color-9">
              <text class="mt-24">{{ option.info.name + " " + option.info.account }}</text>
              <text v-if="option.info.bank || option.info.belong">
                {{ option.info.bank || "" }} {{ option.info.belong || "" }}
              </text>
              <u-image @click="previewQrCode(option.info.qrCode)" v-if="option.info.qrCode" class="mt-20" width="50"
                height="50" src="/static/img/otc/icon-code.png" />
            </view>
          </view>
        </block>

        <button @click="confirmPayOptions" class="mt-50 fs-36 fw-700 br-50 color-2 bg-23" hover-class="tap-hover"
          style="line-height: 44px; width: 540rpx;">继续</button>
      </view>
    </u-popup>
    <u-popup v-model="showPopup.captcha" @input="changePopup($event, 'captcha')" mode="center" closeable
      :mask-close-able="false" close-icon-color="#fff">
      <view class="br-20 bg-21 p-30" style="width: 600rpx;">
        <label class="fs-36 fw-700">验证手机号</label>
        <text class="mt-30">发送短信验证码到手机</text>
        <text class="mt-20 fs-32">{{ formatPhoneNumber(userInfo.mobile) }}</text>
        <view class="mt-30 fd-row ai-center bg-21 br-20">
          <input v-model="captcha.value" class="f1 color-2 pl-30 pr-30 height-88" placeholder="请输入验证码" type="number"
            maxlength="6" placeholder-class="color-9">
          <button @click="getCaptcha" :disabled="captcha.disabled" hover-class="tap-hover"
            class="m-0 p-0 fs-24 color-2 border-none" plain>
            <label class="jc-center" style="width: 160rpx; height: 40rpx; border-left: #999 2rpx solid;">
              {{ captcha.text }}
            </label>
          </button>
        </view>
        <button @click="submitCaptcha" :disabled="!captcha.value" class="mt-50 fs-36 fw-700 br-50 color-2 bg-23"
          hover-class="tap-hover" style="line-height: 44px; width: 540rpx;">完成</button>
      </view>
    </u-popup>

    <u-popup v-model="showPopup.description" @input="changePopup($event, 'description')" mode="center" closeable
      :mask-close-able="false" close-icon-color="#fff" :mask-custom-style="{ backdropFilter: `blur(10rpx)` }">
      <view class="br-40" style="width: 600rpx; 
        background-color: rgba(255,255,255,0.05);
        box-shadow: 0 8rpx 4r0px 0 rgba(0,0,0,0.05), 0 16rpx 80rpx 0 rgba(0,0,0,0.05);
        border: 2rpx solid rgba(255,255,255,0.2);">
        <label class="fs-36 fw-700 jc-center mt-30 color-27">规则说明</label>
        <scroll-view scroll-y class="mt-30 mb-30 lh-2" style="max-height: 30vh;">
          <view class="pl-30 pr-30 color-27" style="white-space: pre-wrap; word-wrap: break-word;">
            <text>1.交易中心开放时间：早上10：00-晚上20：00</text>
            <text>2.订单匹配后1小时内支付订单即可完成。</text>
            <text>3.求购订单匹配成功会有短信通知买家，买家付款后也会短信通知卖家。请大家注意查收短信！</text>
            <text>4.有任何问题可联系客服</text>
          </view>
        </scroll-view>
      </view>
    </u-popup>
    <u-popup v-model="showPopup.password" @input="changePopup($event, 'password')" mode="center" closeable
      close-icon-color="#fff" :mask-close-able="false">
      <view class="bg-22 oh br-20" style="width: 90vw;">
        <view class="mt-30 ai-center">
          <text class="mt-16 mb-30 color-2 fs-32 fw-700">请输入支付密码</text>
          <u-message-input @change="inputPayPassword" @finish="submitCaptcha" focus width="80" :maxlength="6" space="5"
            dot-fill />
        </view>
        <view @click="uniNavigator({ url: `/pages/client/main/setPayPassword` })" hover-class="tap-hover"
          class="mt-10 mb-30 p-20 as-center ml-12 color-5" style="text-decoration: underline;">
          忘记支付密码？
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts" setup>

import { useMapState } from "@/common/libs/store";
import { debounce, formatPhoneNumber, pager, uniNavigator } from "@/common/libs/utils";
import { onLoad, onPullDownRefresh, onReachBottom, onShow } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";

const { $config } = getApp().globalData!;
const { theme } = useMapState(["theme"]);

const priceRange = reactive({
  list: [
    {
      text: "2",
      value: 1
    },
    {
      text: "10",
      value: 2
    },
    {
      text: "50",
      value: 3
    },
    {
      text: "100",
      value: 4
    },
    {
      text: "200",
      value: 5
    },
    {
      text: "500",
      value: 6
    },
  ],
  current: -1
});
const showPopup = reactive({
  sell: false,
  payable: false,
  captcha: false,
  description: true,
  password: false
});
const payOptions = reactive({
  aliPay: {
    text: "支付宝",
    color: "#1677ff",
    value: 1,
    info: {
      account: "",
      name: "",
      qrCode: ""
    }
  },
  weChat: {
    text: "微信",
    color: "#1aad19",
    value: 2,
    info: {
      account: "",
      name: "",
      qrCode: ""
    }
  },
  bankCard: {
    text: "银行卡",
    color: "#ffb829",
    value: 3,
    info: {
      account: "",
      name: "",
      bank: "",
      belong: ""
    }
  },
  usdt: {
    text: "USDT",
    value: 4,
    color: "#27a17c",
    info: {
      account: "",
      name: "",
    },
  }
});
const sellOrders = reactive({
  page: 0,
  limit: 20,
  list: [] as any[],
  search: "",
  cache: {
    page: 1,
    list: [] as any[],
    status: "nomore"
  },
  next: false,
});

const mapPayOptionsKey = { 1: "aliPay", 2: "weChat", 3: "bankCard", 4: "usdt" };

const tradeInfo = ref<AnyObject>({});

const currentOrder = ref<AnyObject>({});
const userInfo = ref<AnyObject>({});

const captcha = reactive({
  text: "获取验证码",
  errorMessage: "验证码输入有误",
  disabled: false,
  count: 60,
  timer: null as any,
  value: "",
  field: "code",
  rule: /^[0-9]{4,8}$/
});
const payPassword = ref("");

onLoad(() => {
  uni.getStorage({
    key: $config.STORAGE_KEY_USER_INFO,
    success(data) {
      userInfo.value = data;
    }
  });
});

onReachBottom(() => {
  getSellOrders();
});

onShow(() => {
  sellOrders.search = "";
  search();
  getTradeInfo();
});

onPullDownRefresh(() => {
  sellOrders.search = "";
  search();
  getTradeInfo();
  setTimeout(uni.stopPullDownRefresh, 360);
});

const changePopup = (e: boolean, popupKey: keyof typeof showPopup) => {
  showPopup[popupKey] = e;
}

const getTradeInfo = () => {
  uni.request({
    url: "/tradeInfo",
    success({ data }: any) {
      tradeInfo.value = data;
    }
  });
}

const inputPayPassword = (val: string) => {
  payPassword.value = val;
}

const search = debounce(() => {
  if (sellOrders.cache.status === "loading") return;
  sellOrders.page = 0;
  sellOrders.limit = 20;
  sellOrders.list = [];
  sellOrders.cache = {
    page: 1,
    list: [] as any[],
    status: "nomore"
  }

  getSellOrders();
});

const getSellOrders = () => {
  pager({
    url: "/tradeList",
    data: {
      mobile: sellOrders.search,
      cls: priceRange.list[priceRange.current]?.value || 0
    }
  }, sellOrders);
}

const checkedPriceRange = (index: number) => {
  if (sellOrders.cache.status === "loading") {
    uni.showToast({ title: "数据正在努力加载中...", icon: "none" });
    return;
  }

  priceRange.current = priceRange.current === index ? -1 : index;
  search();
}

const sell = (item: AnyObject) => {
  currentOrder.value = item;
  showPopup.sell = true;
}

const confirmSell = () => {
  uni.showToast({ icon: "loading" });
  payOptions.aliPay.info = {
    account: "",
    name: "",
    qrCode: ""
  };
  payOptions.weChat.info = {
    account: "",
    name: "",
    qrCode: ""
  };
  payOptions.bankCard.info = {
    account: "",
    name: "",
    bank: "",
    belong: ""
  };
  payOptions.usdt.info = {
    account: "",
    name: "",
  };
  uni.request({
    url: "/accountList",
    success({ data }: any) {
      showPopup.payable = true;
      data.forEach((item: AnyObject) => {
        const { info }: any = payOptions[<keyof typeof payOptions>mapPayOptionsKey[item.type as keyof typeof mapPayOptionsKey]];
        info.account = item.number || "";
        info.name = item.username || "";
        item.url && (info.qrCode = item.url || "");
        item.bank_address && (info.belong = item.bank_address || "");
        item.bank_name && (info.bank = item.bank_name || "");
      });
      uni.hideToast();
    }
  })
}

const setPayOption = (key: string) => {
  showPopup.payable = false;
  uniNavigator({ url: `/pages/client/otc/payableWay?type=${key}` })
}

const previewQrCode = (url: string) => {
  url && uni.previewImage({ urls: [url] });
}

const confirmPayOptions = () => {
  const options = Object.values(payOptions).filter(item => currentOrder.value.pay_type.includes(item.value));

  const availableOptions = options.filter(item => Boolean(item.info.account))

  if (availableOptions.length < 2) {
    uni.showToast({ title: "请至少完善两种及以上收款方式", icon: "none" });
    return;
  }

  showPopup.payable = false;
  // showPopup.captcha = true;
  showPopup.password = true;
}

const countDown = () => {
  captcha.disabled = true;

  const intervalTask = () => {
    captcha.count--;
    captcha.text = `${captcha.count}S`;

    if (captcha.count <= 0) {
      captcha.disabled = false;
      captcha.text = "重新获取";
      captcha.count = 60;
      captcha.timer && clearInterval(captcha.timer);
      captcha.timer = null;
    }
    return intervalTask;
  }
  captcha.timer = setInterval(intervalTask(), 1000);
}

const getCaptcha = () => {
  if (captcha.disabled) return;
  uni.showToast({ icon: "loading", mask: true });
  countDown();
  uni.request({
    url: "/sendSms",
    data: { mobile: userInfo.value.mobile, type: "verify" },
    success: () => uni.showToast({ title: "发送成功", icon: "none" })
  });
}

const submitCaptcha = () => {
  uni.showToast({ icon: "loading", mask: true });
  // showPopup.captcha = false;
  showPopup.password = false;
  uni.request({
    url: "/tradeSell",
    data: {
      order_id: currentOrder.value.id,
      // code: captcha.value
      code: payPassword.value
    },
    success() {
      showPopup.sell = false;
      captcha.value = "";
      uni.navigateTo({ url: "/pages/client/otc/order?type=1&status=1" });
      uni.hideToast();
    }
  });
}

</script>

<style lang="scss">
page {
  background-color: $uni-bg-color-otc;
  color: $uni-text-color-otc;
}
</style>
<style lang="scss" scoped>
button[disabled] {
  background-color: transparent;
}

.light,
.dark {
  padding: 0 0 72px;
}

.header {
  position: fixed;
  z-index: 99;
  top: 0;
  padding: var(--window-top) 30rpx 0;
  left: 0;
  right: 0;
  left: var(--window-left);
  right: var(--window-right);
  box-sizing: content-box;
  height: 88rpx;
}

.footer {
  position: fixed;
  z-index: 99;
  bottom: 0;
  left: 0;
  right: 0;
  left: var(--window-left);
  right: var(--window-right);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>